use std::{
    fs::{remove_file, OpenOptions},
    io::{Error, Write},
    path::Path,
    time::{SystemTime, UNIX_EPOCH},
};

use crate::{db::models::Contract, schema::{material::dsl::*, contract}};
use actix_multipart::Multipart;
use actix_web::{
    post,
    web::{self, Bytes, Data, Json},
    HttpResponse,
};
use chrono::{Local, NaiveDate, TimeZone};
use diesel::{
    dsl::{exists, sql},
    insert_into, select,
    sql_types::{Integer, VarChar},
    update,
};
use diesel::{prelude::*, sql_types::Bool};
use futures::StreamExt;
use xl::{ExcelValue, Workbook, Worksheet};

use crate::{api::Page, db::models::Material, schema::material, DbPool};

#[derive(Debug, serde::Deserialize)]
pub struct PageMaterialReq {
    page: i64,
    size: i64,
    keyword: String,
    contract_id: i32,
}

#[derive(Debug, serde::Serialize, Queryable)]
pub struct MaterialVo {
    pub id: i32,
    pub contract_id: i32,
    pub delivery_date: i64,
    pub delivery_numer: Option<String>,
    pub affiliation: Option<String>,
    pub category: Option<String>,
    pub name: String,
    pub specification: String,
    pub unit: Option<String>,
    pub verify_number: f64,
    pub price: f64,
    pub verify_amount: Option<f64>,
    pub comment: Option<String>,
    pub verify_date: Option<i64>,
    pub verified: Option<i32>,
    pub contract: Contract,
}

const SIZE_MAX: i64 = 50000000000;
const SIZE_INVERSE: i64 = -1;

#[post("/page")]
async fn page_materials(
    db: Data<DbPool>,
    request: web::Json<PageMaterialReq>,
) -> Json<Page<(Material, Contract)>> {
    let req = request.0;
    let data = web::block(move || {
        let mut conn = db.get().unwrap();
        let mut size = req.size;
        if req.size.eq(&SIZE_INVERSE) {
            size = SIZE_MAX;
        }
        let data: Result<Vec<(Material, Contract)>, _> = material::table
            .inner_join(contract::table)
            .filter(
                sql::<Bool>("name like ")
                    .bind::<VarChar, _>(format!("%{}%", req.keyword))
                    .sql(" and ( contract_id = ")
                    .bind::<Integer, _>(req.contract_id)
                    .sql(" or -1 = ")
                    .bind::<Integer, _>(req.contract_id)
                    .sql(" )"),
            )
            .limit(size)
            .offset((req.page - 1) * size)
            .select((Material::as_select(), Contract::as_select()))
            .load::<(Material, Contract)>(&mut conn);

        let c: Result<i64, _> = material
            .select(diesel::dsl::count(material::id))
            .filter(
                sql::<Bool>("name like ")
                    .bind::<VarChar, _>(format!("%{}%", req.keyword))
                    .sql(" and ( contract_id = ")
                    .bind::<Integer, _>(req.contract_id)
                    .sql(" or -1 = ")
                    .bind::<Integer, _>(req.contract_id)
                    .sql(" )"),
            )
            .first(&mut conn);
        match data {
            Ok(d) => Page {
                total: c.unwrap(),
                content: d,
            },
            Err(e) => {
                println!("{:?}", e);
                return Page {
                    total: 0,
                    content: vec![],
                };
            }
        }
    })
    .await;
    Json(data.unwrap())
}

#[post("/create")]
async fn create_material(db: Data<DbPool>, request: web::Json<Material>) -> HttpResponse {
    let req = request.0;
    let data = web::block(move || {
        let mut conn = db.get().unwrap();
        // 判断主合同是否存在
        let exists: Result<bool, diesel::result::Error> = select(exists(
            contract::dsl::contract.filter(contract::id.eq(&req.contract_id)),
        ))
        .get_result(&mut conn);
        if let Ok(s) = exists {
            if !s {
                return 3;
            }
        }

        let result = insert_into(material).values(&req).execute(&mut conn);
        match result {
            Ok(a) => a,
            Err(e) => {
                println!("{:?}", e);
                return 0;
            }
        }
    })
    .await;
    match data.unwrap() {
        0 => HttpResponse::BadRequest().body("新建失败"),
        3 => HttpResponse::BadRequest().body("主合同不存在"),
        _ => HttpResponse::Ok().json(true),
    }
}

#[post("/update")]
async fn update_material(db: Data<DbPool>, request: web::Json<Material>) -> HttpResponse {
    let req = request.0;
    let data = web::block(move || {
        let mut conn = db.get().unwrap();

        // 判断主合同是否存在
        let exists: Result<bool, diesel::result::Error> = select(exists(
            contract::dsl::contract.filter(contract::id.eq(&req.contract_id)),
        ))
        .get_result(&mut conn);
        if let Ok(s) = exists {
            if !s {
                return 3;
            }
        }

        let result: Result<usize, _> = update(material.filter(material::id.eq(req.id)))
            .set((
                material::contract_id.eq(req.contract_id),
                material::delivery_date.eq(req.delivery_date),
                material::delivery_numer.eq(req.delivery_numer),
                material::affiliation.eq(req.affiliation),
                material::category.eq(req.category),
                material::name.eq(req.name),
                material::specification.eq(req.specification),
                material::unit.eq(req.unit),
                material::verify_number.eq(req.verify_number),
                material::price.eq(req.price),
                material::verify_amount.eq(req.verify_amount),
                material::comment.eq(req.comment),
                material::verify_date.eq(req.verify_date),
                material::verified.eq(req.verified),
                material::ext_name1.eq(req.ext_name1),
                material::ext_name2.eq(req.ext_name2),
                material::ext_name3.eq(req.ext_name3),
                material::ext_name4.eq(req.ext_name4),
                material::ext_name5.eq(req.ext_name5),
                material::ext_name6.eq(req.ext_name6),
                material::ext_name7.eq(req.ext_name7),
                material::ext_name8.eq(req.ext_name8),
                material::ext_name9.eq(req.ext_name9),
                material::ext_name10.eq(req.ext_name10),
                material::ext_name11.eq(req.ext_name11),
                material::ext_name12.eq(req.ext_name12),
                material::ext_name13.eq(req.ext_name13),
                material::ext_name14.eq(req.ext_name14),
                material::ext_name15.eq(req.ext_name15),
                material::ext_name16.eq(req.ext_name16),
                material::ext_name17.eq(req.ext_name17),
                material::ext_name18.eq(req.ext_name18),
                material::ext_name19.eq(req.ext_name19),
                material::ext_name20.eq(req.ext_name20),
                material::ext_value1.eq(req.ext_value1),
                material::ext_value2.eq(req.ext_value2),
                material::ext_value3.eq(req.ext_value3),
                material::ext_value4.eq(req.ext_value4),
                material::ext_value5.eq(req.ext_value5),
                material::ext_value6.eq(req.ext_value6),
                material::ext_value7.eq(req.ext_value7),
                material::ext_value8.eq(req.ext_value8),
                material::ext_value9.eq(req.ext_value9),
                material::ext_value10.eq(req.ext_value10),
                material::ext_value11.eq(req.ext_value11),
                material::ext_value12.eq(req.ext_value12),
                material::ext_value13.eq(req.ext_value13),
                material::ext_value14.eq(req.ext_value14),
                material::ext_value15.eq(req.ext_value15),
                material::ext_value16.eq(req.ext_value16),
                material::ext_value17.eq(req.ext_value17),
                material::ext_value18.eq(req.ext_value18),
                material::ext_value19.eq(req.ext_value19),
                material::ext_value20.eq(req.ext_value20),
            ))
            .execute(&mut conn);
        match result {
            Ok(_) => 200,
            _ => 0,
        }
    })
    .await;
    match data.unwrap() {
        0 => HttpResponse::BadRequest().body("更新失败"),
        3 => HttpResponse::BadRequest().body("主合同不存在"),
        _ => HttpResponse::Ok().json(true),
    }
}

#[derive(Debug, serde::Deserialize)]
pub struct DeleteMaterialReq {
    id: i32,
}

#[post("/delete")]
async fn delete_material(db: Data<DbPool>, request: web::Json<DeleteMaterialReq>) -> HttpResponse {
    let req = request.0;
    let data = web::block(move || {
        let mut conn = db.get().unwrap();
        let result = diesel::delete(material.filter(material::id.eq(req.id))).execute(&mut conn);
        match result {
            Ok(d) => d,
            _ => 0,
        }
    })
    .await;
    match data.unwrap() {
        0 => HttpResponse::BadRequest().body("未找到记录"),
        _ => HttpResponse::Ok().json(true),
    }
}

#[derive(Debug, serde::Deserialize)]
pub struct VerifyAmountReq {
    id: i32,
    verify_amount: f64,
}

#[post("/verify_amount")]
async fn verify_amount(db: Data<DbPool>, request: web::Json<VerifyAmountReq>) -> HttpResponse {
    let req = request.0;
    let data = web::block(move || {
        let mut conn = db.get().unwrap();
        let result = diesel::update(material.filter(material::id.eq(req.id)))
            .set(material::verify_amount.eq(req.verify_amount))
            .execute(&mut conn);
        match result {
            Ok(d) => d,
            _ => 0,
        }
    })
    .await;
    match data.unwrap() {
        0 => HttpResponse::BadRequest().body("未找到记录"),
        1 => HttpResponse::Ok().json(true),
        _ => HttpResponse::BadRequest().body("更新失败"),
    }
}

#[post("/upload")]
async fn import_material(db: Data<DbPool>, mut payload: Multipart) -> HttpResponse {
    let a = payload.next().await;

    if let Some(field) = a {
        match field {
            Ok(mut f) => {
                if let Some(content) = f.next().await {
                    let file_name = format!(
                        "import_{:?}.xlsx",
                        SystemTime::now()
                            .duration_since(UNIX_EPOCH)
                            .unwrap()
                            .as_millis()
                    );
                    match save_file(file_name.clone(), content.unwrap()) {
                        Ok(_) => {
                            if let Ok(mut wb) = xl::Workbook::open(&file_name) {
                                let sheets = wb.sheets();
                                let sheet_names = sheets.by_name();
                                if let Some(sheet) = sheets.get(sheet_names[0]) {
                                    // 入库
                                    let mut conn = db.get().unwrap();
                                    let data: Result<Vec<(i32, String)>, _> = contract::table
                                        .select((contract::id, contract::no))
                                        .load::<(i32, String)>(&mut conn);
                                    if let Err(_) = data {
                                        // 删除文件
                                        delete_file(file_name);
                                        return HttpResponse::BadRequest()
                                            .json("请先录入合同信息后再进行导入！");
                                    }
                                    match parse_excel_data(sheet, wb, &data.unwrap()) {
                                        Ok(materials) => {
                                            // 判断主合同是否存在
                                            let exists: Result<bool, diesel::result::Error> =
                                                select(exists(contract::dsl::contract.filter(
                                                    contract::id.eq(&materials[0].contract_id),
                                                )))
                                                .get_result(&mut conn);
                                            if let Ok(s) = exists {
                                                if !s {
                                                    // 删除文件
                                                    delete_file(file_name);
                                                    return HttpResponse::BadRequest()
                                                        .json("合同不存在");
                                                }
                                            }

                                            let result = insert_into(material)
                                                .values(&materials)
                                                .execute(&mut conn);
                                            match result {
                                                Ok(a) => {
                                                    // 删除文件
                                                    delete_file(file_name);
                                                    return HttpResponse::Ok()
                                                        .json(format!("成功导入{}条数据！", a));
                                                }
                                                Err(e) => {
                                                    // 删除文件
                                                    delete_file(file_name);
                                                    println!("{:?}", e);
                                                    return HttpResponse::BadRequest()
                                                        .json("导入数据失败");
                                                }
                                            }
                                        }
                                        Err(e) => {
                                            // 删除文件
                                            delete_file(file_name);
                                            return HttpResponse::BadRequest().json(e);
                                        }
                                    }
                                } else {
                                    // 删除文件
                                    delete_file(file_name);
                                    return HttpResponse::BadRequest().json("读取excel内容失败");
                                }
                            } else {
                                // 删除文件
                                delete_file(file_name);
                                return HttpResponse::BadRequest().json("读取excel文件失败");
                            }
                            // let data = web::block(move || {

                            // })
                            // .await;
                            // if let Ok(da) = data {
                            //     return da;
                            // } else {
                            //     return HttpResponse::BadRequest().body("导入失败");
                            // }
                        }

                        _ => {
                            return HttpResponse::BadRequest().body("导入失败");
                        }
                    }
                }
            }
            _ => {
                return HttpResponse::BadRequest().body("导入失败");
            }
        }
    }
    return HttpResponse::BadRequest().body("导入失败");
}

fn parse_excel_data(
    sheet: &Worksheet,
    mut wb: Workbook,
    contract_data: &Vec<(i32, String)>,
) -> Result<Vec<Material>, &'static str> {
    const FIX_HEADER: &[&str] = &[
        "送货日期",
        "合同",
        "产品单号",
        "所属公司",
        "类别",
        "名称",
        "规格",
        "单位",
        "核对数量",
        "单价",
        "核对金额",
        "备注",
    ];
    let mut row = sheet.rows(&mut wb);
    if let Some(title_row) = row.next() {
        let mut materials = vec![];
        if FIX_HEADER.len() > title_row.0.len() {
            return Err("表头不匹配，请按照模板文件中表头进行录入后重试！");
        }
        let mut ext_header = vec![];
        for i in 0..title_row.0.len() {
            if i < FIX_HEADER.len() {
                if let ExcelValue::String(s) = &title_row.0[i].value {
                    if s.trim().ne(FIX_HEADER[i]) {
                        return Err("表头不匹配，请按照模板文件中表头进行录入后重试！");
                    }
                } else {
                    return Err("表头不匹配，请按照模板文件中表头进行录入后重试！");
                }
            } else {
                if let ExcelValue::String(ss) = &title_row.0[i].value {
                    ext_header.insert(ext_header.len(), ss.trim().to_string());
                } else {
                    return Err("标题栏必须是字符串");
                }
            }
        }
        while let Some(content_row) = row.next() {
            if let ExcelValue::None = content_row.0[0].value {
                break;
            } else {
                if let ExcelValue::String(s) = &content_row.0[0].value {
                    if s.trim().eq("") {
                        break;
                    }
                }
            }

            let mut m = Material::default();
            for i in 0..content_row.0.len() {
                let value = &content_row.0[i].value;
                match i {
                    0 => match value {
                        ExcelValue::String(dd) => {
                            if let Ok(d) = NaiveDate::parse_from_str(dd.trim(), "%Y-%m-%d") {
                                let dt = d.and_hms_opt(0, 0, 0).unwrap();
                                m.delivery_date = Local
                                    .from_local_datetime(&dt)
                                    .single()
                                    .unwrap()
                                    .timestamp_millis();
                            } else if let Ok(d) = NaiveDate::parse_from_str(dd.trim(), "%Y/%m/%d") {
                                let dt = d.and_hms_opt(0, 0, 0).unwrap();
                                m.delivery_date = Local
                                    .from_local_datetime(&dt)
                                    .single()
                                    .unwrap()
                                    .timestamp_millis();
                            } else {
                                return Err("无法解析送货日期1");
                            }
                        }
                        ExcelValue::Date(d) => {
                            let dt = d.and_hms_opt(0, 0, 0).unwrap();
                            m.delivery_date = Local
                                .from_local_datetime(&dt)
                                .single()
                                .unwrap()
                                .timestamp_millis();
                        }
                        ExcelValue::DateTime(d) => {
                            m.delivery_date = Local
                                .from_local_datetime(&d)
                                .single()
                                .unwrap()
                                .timestamp_millis();
                        }
                        _ => {
                            return Err("无法解析送货日期2");
                        }
                    },
                    1 => {
                        if let ExcelValue::String(cs) = value {
                            let mut found = false;
                            for cd in contract_data {
                                if cd.1.eq(cs.trim()) {
                                    m.contract_id = cd.0;
                                    found = true;
                                    break;
                                }
                            }
                            if !found {
                                return Err("合同号无效");
                            }
                        } else {
                            return Err("合同号必须填入");
                        }
                    }
                    2 => match value {
                        ExcelValue::String(dn) => {
                            m.delivery_numer = Some(dn.trim().to_string());
                        }
                        ExcelValue::None => {
                            m.delivery_numer = None;
                        }
                        ExcelValue::Number(v) => {
                            m.delivery_numer = Some(v.to_string());
                        }
                        _ => {
                            return Err("产品单号必须为字符串");
                        }
                    },
                    3 => match value {
                        ExcelValue::String(dn) => {
                            m.affiliation = Some(dn.trim().to_string());
                        }
                        ExcelValue::None => {
                            m.affiliation = None;
                        }
                        ExcelValue::Number(v) => {
                            m.affiliation = Some(v.to_string());
                        }
                        _ => {
                            return Err("所属公司必须为字符串");
                        }
                    },
                    4 => match value {
                        ExcelValue::String(dn) => {
                            m.category = Some(dn.trim().to_string());
                        }
                        ExcelValue::None => {
                            m.category = None;
                        }
                        ExcelValue::Number(v) => {
                            m.category = Some(v.to_string());
                        }
                        _ => {
                            return Err("类别必须为字符串");
                        }
                    },
                    5 => match value {
                        ExcelValue::String(dn) => {
                            m.name = dn.trim().to_string();
                        }
                        ExcelValue::None => {
                            m.name = "".to_string();
                        }
                        ExcelValue::Number(v) => {
                            m.name = v.to_string();
                        }
                        _ => {
                            return Err("名称必须是字符串");
                        }
                    },
                    6 => match value {
                        ExcelValue::String(dn) => {
                            m.specification = dn.trim().to_string();
                        }
                        ExcelValue::None => {
                            m.specification = "".to_string();
                        }
                        ExcelValue::Number(v) => {
                            m.specification = v.to_string();
                        }
                        _ => {
                            return Err("规格必须是字符串");
                        }
                    },
                    7 => match value {
                        ExcelValue::String(dn) => {
                            m.unit = Some(dn.trim().to_string());
                        }
                        ExcelValue::None => {
                            m.unit = None;
                        }
                        ExcelValue::Number(v) => {
                            m.unit = Some(v.to_string());
                        }
                        _ => {
                            return Err("单位必须字符串");
                        }
                    },
                    8 => match value {
                        ExcelValue::Number(vv) => {
                            m.verify_number = *vv;
                        }
                        ExcelValue::None => {
                            m.verify_number = 0.0;
                        }
                        _ => {
                            return Err("核对数量必须是数字");
                        }
                    },
                    9 => match value {
                        ExcelValue::Number(vv) => {
                            m.price = *vv;
                        }
                        ExcelValue::None => {
                            m.price = 0.0;
                        }
                        _ => {
                            return Err("单价必须是数字");
                        }
                    },
                    10 => match value {
                        ExcelValue::Number(vv) => {
                            m.verify_amount = Some(*vv);
                        }
                        ExcelValue::None => {
                            m.verify_amount = None;
                        }
                        _ => {
                            return Err("核对金额必须是数字");
                        }
                    },
                    11 => match value {
                        ExcelValue::String(dn) => {
                            m.comment = Some(dn.trim().to_string());
                        }
                        ExcelValue::None => {
                            m.comment = None;
                        }
                        ExcelValue::Number(v) => {
                            m.comment = Some(v.to_string());
                        }
                        _ => {
                            return Err("备注必须是字符串");
                        }
                    },
                    12 => match value {
                        ExcelValue::String(es) => {
                            let en = &ext_header[i - FIX_HEADER.len()];
                            m.ext_name1 = Some(en.clone());
                            m.ext_value1 = Some(es.trim().to_string());
                        }
                        ExcelValue::None => {
                            m.ext_value1 = None;
                        }
                        ExcelValue::Number(v) => {
                            m.ext_value1 = Some(v.to_string());
                        }
                        _ => {
                            return Err("扩展字段必须是字符串类型");
                        }
                    },
                    13 => match value {
                        ExcelValue::String(es) => {
                            let en = &ext_header[i - FIX_HEADER.len()];
                            m.ext_name2 = Some(en.clone());
                            m.ext_value2 = Some(es.trim().to_string());
                        }
                        ExcelValue::None => {
                            m.ext_value2 = None;
                        }
                        ExcelValue::Number(v) => {
                            m.ext_value2 = Some(v.to_string());
                        }
                        _ => {
                            return Err("扩展字段必须是字符串类型");
                        }
                    },
                    14 => match value {
                        ExcelValue::String(es) => {
                            let en = &ext_header[i - FIX_HEADER.len()];
                            m.ext_name3 = Some(en.clone());
                            m.ext_value3 = Some(es.trim().to_string());
                        }
                        ExcelValue::None => {
                            m.ext_value3 = None;
                        }
                        ExcelValue::Number(v) => {
                            m.ext_value3 = Some(v.to_string());
                        }
                        _ => {
                            return Err("扩展字段必须是字符串类型");
                        }
                    },
                    15 => match value {
                        ExcelValue::String(es) => {
                            let en = &ext_header[i - FIX_HEADER.len()];
                            m.ext_name4 = Some(en.clone());
                            m.ext_value4 = Some(es.trim().to_string());
                        }
                        ExcelValue::None => {
                            m.ext_value4 = None;
                        }
                        ExcelValue::Number(v) => {
                            m.ext_value4 = Some(v.to_string());
                        }
                        _ => {
                            return Err("扩展字段必须是字符串类型");
                        }
                    },
                    16 => match value {
                        ExcelValue::String(es) => {
                            let en = &ext_header[i - FIX_HEADER.len()];
                            m.ext_name5 = Some(en.clone());
                            m.ext_value5 = Some(es.trim().to_string());
                        }
                        ExcelValue::None => {
                            m.ext_value5 = None;
                        }
                        ExcelValue::Number(v) => {
                            m.ext_value5 = Some(v.to_string());
                        }
                        _ => {
                            return Err("扩展字段必须是字符串类型");
                        }
                    },
                    17 => match value {
                        ExcelValue::String(es) => {
                            let en = &ext_header[i - FIX_HEADER.len()];
                            m.ext_name6 = Some(en.clone());
                            m.ext_value6 = Some(es.trim().to_string());
                        }
                        ExcelValue::None => {
                            m.ext_value6 = None;
                        }
                        ExcelValue::Number(v) => {
                            m.ext_value6 = Some(v.to_string());
                        }
                        _ => {
                            return Err("扩展字段必须是字符串类型");
                        }
                    },
                    18 => match value {
                        ExcelValue::String(es) => {
                            let en = &ext_header[i - FIX_HEADER.len()];
                            m.ext_name7 = Some(en.clone());
                            m.ext_value7 = Some(es.trim().to_string());
                        }
                        ExcelValue::None => {
                            m.ext_value7 = None;
                        }
                        ExcelValue::Number(v) => {
                            m.ext_value7 = Some(v.to_string());
                        }
                        _ => {
                            return Err("扩展字段必须是字符串类型");
                        }
                    },
                    19 => match value {
                        ExcelValue::String(es) => {
                            let en = &ext_header[i - FIX_HEADER.len()];
                            m.ext_name8 = Some(en.clone());
                            m.ext_value8 = Some(es.trim().to_string());
                        }
                        ExcelValue::None => {
                            m.ext_value8 = None;
                        }
                        ExcelValue::Number(v) => {
                            m.ext_value8 = Some(v.to_string());
                        }
                        _ => {
                            return Err("扩展字段必须是字符串类型");
                        }
                    },
                    20 => match value {
                        ExcelValue::String(es) => {
                            let en = &ext_header[i - FIX_HEADER.len()];
                            m.ext_name9 = Some(en.clone());
                            m.ext_value9 = Some(es.trim().to_string());
                        }
                        ExcelValue::None => {
                            m.ext_value9 = None;
                        }
                        ExcelValue::Number(v) => {
                            m.ext_value9 = Some(v.to_string());
                        }
                        _ => {
                            return Err("扩展字段必须是字符串类型");
                        }
                    },
                    21 => match value {
                        ExcelValue::String(es) => {
                            let en = &ext_header[i - FIX_HEADER.len()];
                            m.ext_name10 = Some(en.clone());
                            m.ext_value10 = Some(es.trim().to_string());
                        }
                        ExcelValue::None => {
                            m.ext_value10 = None;
                        }
                        ExcelValue::Number(v) => {
                            m.ext_value10 = Some(v.to_string());
                        }
                        _ => {
                            return Err("扩展字段必须是字符串类型");
                        }
                    },
                    22 => match value {
                        ExcelValue::String(es) => {
                            let en = &ext_header[i - FIX_HEADER.len()];
                            m.ext_name11 = Some(en.clone());
                            m.ext_value11 = Some(es.trim().to_string());
                        }
                        ExcelValue::None => {
                            m.ext_value11 = None;
                        }
                        ExcelValue::Number(v) => {
                            m.ext_value11 = Some(v.to_string());
                        }
                        _ => {
                            return Err("扩展字段必须是字符串类型");
                        }
                    },
                    23 => match value {
                        ExcelValue::String(es) => {
                            let en = &ext_header[i - FIX_HEADER.len()];
                            m.ext_name12 = Some(en.clone());
                            m.ext_value12 = Some(es.trim().to_string());
                        }
                        ExcelValue::None => {
                            m.ext_value12 = None;
                        }
                        ExcelValue::Number(v) => {
                            m.ext_value12 = Some(v.to_string());
                        }
                        _ => {
                            return Err("扩展字段必须是字符串类型");
                        }
                    },
                    24 => match value {
                        ExcelValue::String(es) => {
                            let en = &ext_header[i - FIX_HEADER.len()];
                            m.ext_name13 = Some(en.clone());
                            m.ext_value13 = Some(es.trim().to_string());
                        }
                        ExcelValue::None => {
                            m.ext_value13 = None;
                        }
                        ExcelValue::Number(v) => {
                            m.ext_value13 = Some(v.to_string());
                        }
                        _ => {
                            return Err("扩展字段必须是字符串类型");
                        }
                    },
                    25 => match value {
                        ExcelValue::String(es) => {
                            let en = &ext_header[i - FIX_HEADER.len()];
                            m.ext_name14 = Some(en.clone());
                            m.ext_value14 = Some(es.trim().to_string());
                        }
                        ExcelValue::None => {
                            m.ext_value14 = None;
                        }
                        ExcelValue::Number(v) => {
                            m.ext_value14 = Some(v.to_string());
                        }
                        _ => {
                            return Err("扩展字段必须是字符串类型");
                        }
                    },
                    26 => match value {
                        ExcelValue::String(es) => {
                            let en = &ext_header[i - FIX_HEADER.len()];
                            m.ext_name15 = Some(en.clone());
                            m.ext_value15 = Some(es.trim().to_string());
                        }
                        ExcelValue::None => {
                            m.ext_value15 = None;
                        }
                        ExcelValue::Number(v) => {
                            m.ext_value15 = Some(v.to_string());
                        }
                        _ => {
                            return Err("扩展字段必须是字符串类型");
                        }
                    },
                    27 => match value {
                        ExcelValue::String(es) => {
                            let en = &ext_header[i - FIX_HEADER.len()];
                            m.ext_name16 = Some(en.clone());
                            m.ext_value16 = Some(es.trim().to_string());
                        }
                        ExcelValue::None => {
                            m.ext_value16 = None;
                        }
                        ExcelValue::Number(v) => {
                            m.ext_value16 = Some(v.to_string());
                        }
                        _ => {
                            return Err("扩展字段必须是字符串类型");
                        }
                    },
                    28 => match value {
                        ExcelValue::String(es) => {
                            let en = &ext_header[i - FIX_HEADER.len()];
                            m.ext_name17 = Some(en.clone());
                            m.ext_value17 = Some(es.trim().to_string());
                        }
                        ExcelValue::None => {
                            m.ext_value17 = None;
                        }
                        ExcelValue::Number(v) => {
                            m.ext_value17 = Some(v.to_string());
                        }
                        _ => {
                            return Err("扩展字段必须是字符串类型");
                        }
                    },
                    29 => match value {
                        ExcelValue::String(es) => {
                            let en = &ext_header[i - FIX_HEADER.len()];
                            m.ext_name18 = Some(en.clone());
                            m.ext_value18 = Some(es.trim().to_string());
                        }
                        ExcelValue::None => {
                            m.ext_value18 = None;
                        }
                        ExcelValue::Number(v) => {
                            m.ext_value18 = Some(v.to_string());
                        }
                        _ => {
                            return Err("扩展字段必须是字符串类型");
                        }
                    },
                    30 => match value {
                        ExcelValue::String(es) => {
                            let en = &ext_header[i - FIX_HEADER.len()];
                            m.ext_name19 = Some(en.clone());
                            m.ext_value19 = Some(es.trim().to_string());
                        }
                        ExcelValue::None => {
                            m.ext_value19 = None;
                        }
                        ExcelValue::Number(v) => {
                            m.ext_value19 = Some(v.to_string());
                        }
                        _ => {
                            return Err("扩展字段必须是字符串类型");
                        }
                    },
                    31 => match value {
                        ExcelValue::String(es) => {
                            let en = &ext_header[i - FIX_HEADER.len()];
                            m.ext_name20 = Some(en.clone());
                            m.ext_value20 = Some(es.trim().to_string());
                        }
                        ExcelValue::None => {
                            m.ext_value20 = None;
                        }
                        ExcelValue::Number(v) => {
                            m.ext_value20 = Some(v.to_string());
                        }
                        _ => {
                            return Err("扩展字段必须是字符串类型");
                        }
                    },
                    _ => {}
                }
            }
            materials.insert(materials.len(), m)
        }
        Ok(materials)
    } else {
        return Err("文件头部不正确");
    }
    // for row in sheet.rows(&mut wb) {

    //     let mut cells = vec![];
    //     for cell in row.0 {
    //         cells.insert(0, cell.value);
    //     }
    //     println!("{:?}", cells)
    // }
    // Err("解析文件失败")
}

fn save_file(file_name: String, content: Bytes) -> Result<(), Error> {
    let file_path = Path::new("./").join(file_name);
    let mut f = OpenOptions::new()
        .append(true)
        .write(true)
        .create(true)
        .open(&file_path)
        .unwrap();
    f.write_all(&content)
}

fn delete_file(file_name: String) {
    let file_path = Path::new("./").join(file_name);
    match remove_file(file_path) {
        Err(e) => {
            println!("delete file failed: {}", e);
        }
        _ => (),
    }
}
